<template>
  <div class="min-h-screen bg-gradient-to-br from-indigo-600 via-purple-600 to-pink-500 flex items-center justify-center p-4">
    <GameHeader>
      <div class="stats-card">
        <span>步数</span>
        <span class="animate-pulse">{{ moves }}</span>
      </div>
      <div class="stats-card">
        <span>已配对</span>
        <span class="animate-pulse">{{ matchedPairs }}/8</span>
      </div>
    </GameHeader>
    
    <!-- 游戏内容 -->
    <div class="w-[600px] bg-white/10 backdrop-blur-lg rounded-2xl p-8 shadow-2xl border border-white/20">
      <h1 class="text-4xl font-extrabold text-center mb-6 text-white">
        记忆配对游戏
        <div class="text-base font-normal mt-2 text-white/80">找出所有配对的卡片！</div>
      </h1>
      
      <div class="grid grid-cols-4 gap-3 mb-6">
        <div
          v-for="card in cards"
          :key="card.id"
          class="card-wrapper relative aspect-square rounded-lg transition-all duration-300 transform hover:scale-110 focus:outline-none focus:ring-4 focus:ring-purple-600 focus:ring-opacity-50 overflow-hidden"
          :class="{
            'is-flipped': card.isFlipped || card.isMatched,
            'is-matched': card.isMatched,
            'pointer-events-none': isChecking
          }"
          @click="handleCardClick(card.id)"
        >
          <div class="card-inner">
            <div class="card-front bg-gradient-to-br from-blue-400 to-blue-600"></div>
            <div class="card-back bg-white">
              <span class="text-4xl">{{ card.emoji }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 游戏结束界面 -->
      <GameOver
        v-if="isGameOver"
        title="🎉 恭喜你赢了! 🎉"
        @restart="initializeGame"
      >
        <p class="text-xl text-gray-700">总共用了 {{ moves }} 步</p>
      </GameOver>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import confetti from "canvas-confetti";
import GameHeader from './common/GameHeader.vue'

interface Card {
  id: number;
  emoji: string;
  isFlipped: boolean;
  isMatched: boolean;
}

const emojis = ["🐶", "🐱", "🐭", "🐹", "🐰", "🦊", "🐻", "🐼"];
const cards = ref<Card[]>([]);
const flippedCards = ref<number[]>([]);
const moves = ref(0);
const isGameOver = ref(false);
const isChecking = ref(false);

// 计算已匹配的对数
const matchedPairs = computed(() => {
  return cards.value.filter(card => card.isMatched).length / 2;
});

const initializeGame = () => {
  const shuffledEmojis = [...emojis, ...emojis].sort(() => Math.random() - 0.5);
  cards.value = shuffledEmojis.map((emoji, index) => ({
    id: index,
    emoji,
    isFlipped: false,
    isMatched: false,
  }));
  flippedCards.value = [];
  moves.value = 0;
  isGameOver.value = false;
};

const handleCardClick = (id: number) => {
  const card = cards.value[id];
  
  // 防止重复点击或在检查匹配时点击
  if (
    isChecking.value ||
    flippedCards.value.length === 2 ||
    card.isFlipped ||
    card.isMatched
  ) {
    return;
  }

  // 翻转卡片
  card.isFlipped = true;
  flippedCards.value.push(id);

  if (flippedCards.value.length === 2) {
    moves.value++;
    isChecking.value = true;
    checkForMatch();
  }
};

const checkForMatch = () => {
  const [firstId, secondId] = flippedCards.value;
  const firstCard = cards.value[firstId];
  const secondCard = cards.value[secondId];

  if (firstCard.emoji === secondCard.emoji) {
    // 匹配成功
    firstCard.isMatched = true;
    secondCard.isMatched = true;
    flippedCards.value = [];
    isChecking.value = false;

    // 检查游戏是否结束
    if (cards.value.every((card) => card.isMatched)) {
      isGameOver.value = true;
      celebrateWin();
    }
  } else {
    // 匹配失败，延迟翻回
    setTimeout(() => {
      firstCard.isFlipped = false;
      secondCard.isFlipped = false;
      flippedCards.value = [];
      isChecking.value = false;
    }, 1000);
  }
};

const celebrateWin = () => {
  confetti({
    particleCount: 100,
    spread: 70,
    origin: { y: 0.6 },
  });
};

// 初始化游戏
initializeGame();
</script>

<style scoped>
.card-wrapper {
  perspective: 1000px;
  height: 100px; /* 固定卡片高度 */
}

.card-inner {
  @apply absolute inset-0 transition-transform duration-500;
  transform-style: preserve-3d;
}

.is-flipped .card-inner {
  transform: rotateY(180deg);
}

.card-front,
.card-back {
  @apply absolute inset-0 flex items-center justify-center backface-hidden;
}

.card-back {
  transform: rotateY(180deg);
}

.is-matched .card-back {
  @apply bg-green-100;
  animation: pulse 1s ease-in-out;
}

@keyframes pulse {
  0% { transform: scale(1) rotateY(180deg); }
  50% { transform: scale(1.1) rotateY(180deg); }
  100% { transform: scale(1) rotateY(180deg); }
}

.backface-hidden {
  backface-visibility: hidden;
}
</style>
